package fm.dongman.animefm.view.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.ComicContract
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.adapter.ComicRecommendAdapter
import fm.dongman.animefm.view.adapter.HomeAnimeRecommendAdapter
import fm.dongman.animefm.view.transform.GlideRoundTransform
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.BannerHelper
import fm.dongman.animefm.view.util.SystemHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.BannerViewPager
import fm.dongman.animefm.view.widget.MultiStateLayout
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.ComicModel
import fm.dongman.modellib.model.CommentModel
import fm.dongman.presenterlib.presenter.ComicPresenter
import fm.dongman.presenterlib.util.NetworkHelper
import kotlinx.android.synthetic.main.fragment_comic.*
import kotlinx.android.synthetic.main.item_comic_latest_tucao.view.*
import kotlinx.android.synthetic.main.layout_comic.*
import org.jetbrains.anko.onClick

/**
 * 番剧页面
 * Created by shize on 2017/9/28.
 */
class ComicFragment : BaseFragment(), ComicContract.IComicView {
    private lateinit var mPresenter: ComicContract.IComicPresenter  // 全局数据控制器

    private var mRecommendComicsList: ArrayList<IModel.IComicModel> = ArrayList() //推荐番剧list
    private lateinit var mComicRecommendAdapter: ComicRecommendAdapter     //推荐番剧Adapter

    private var mComicNewCommentsList: ArrayList<IModel.ICommentModel> = ArrayList() //最新槽点
    private lateinit var mComicNewCommentsAdapter: ComicTucaoAdapter    //最新槽点Adapter

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val fragment = inflater?.inflate(R.layout.fragment_comic, container, false)
        ComicPresenter(this, Injection.provideComicRepository(container!!.context))
        return fragment!!
    }

    override fun initData() {
        onStateChanged(MultiStateLayout.LOADING)
        mTbComicTitle.setPadding(0, SystemHelper.getStatusBarHeight(activity), 0, 0)
        mIvComicSearch.onClick {
            val intent = Intent(activity, SingleActivity::class.java)
            intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_SEARCH)
            ActivityHelper.startActivity(activity, intent)
        }
    }

    override fun setPresenter(presenter: ComicContract.IComicPresenter) {
        mPresenter = presenter
    }

    override fun bindData() {
        bindComicButton()
        bindSwipe()
        bindAdapter()
        mPresenter.startLoad()
    }

    private fun bindAdapter() {
        mComicRecommendAdapter = ComicRecommendAdapter(activity, mRecommendComicsList) //推荐番剧初始化
        mRvComicRecommendList.adapter = mComicRecommendAdapter
        mRvComicRecommendList.layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.HORIZONTAL, false)

        mComicNewCommentsAdapter = ComicTucaoAdapter(activity, mComicNewCommentsList) //最新吐槽初始化
        mRvComicNewComments.adapter = mComicNewCommentsAdapter                        //最新吐槽
        mRvComicNewComments.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
    }

    /**
     * 绑定刷新控件
     */
    private fun bindSwipe() {
        mComicSwipeRefreshLayout.setColorSchemeResources(R.color.primary)
        mComicSwipeRefreshLayout.setOnRefreshListener {
            mPresenter.refreshPage()
        }
    }

    /**
     * 绑定番剧按钮
     */
    private fun bindComicButton() {
        // 时间表
        mLlComicTime.onClick {
            val intent = Intent(activity, SingleActivity::class.java)
            intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_TIME_COMIC)
            ActivityHelper.startActivity(activity, intent)
        }
        // 本季度新番
        mNewComic.onClick {
            val intent = Intent(activity, SingleActivity::class.java)
            intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_QUARTER_COMIC)
            ActivityHelper.startActivity(activity, intent)
        }
        // 番剧推荐更多按钮
        mTvComicRecommendMore.onClick {
            ActivityHelper.startActivity(activity, SingleActivity::class.java, mapOf(
                    Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_COMIC_CLASSIFY)
            ), false)
        }
    }

    override fun showNoNetwork() {
        onStateChanged(MultiStateLayout.NET_ERROR)
    }

    override fun showRefreshFailed() {
        mComicSwipeRefreshLayout?.isRefreshing = false
        if (NetworkHelper.isNetworkAvailable(activity)) {
            ToastHelper.getInstance(activity).showError("番剧页面加载失败！")
            return
        }
    }

    @SuppressLint("SetTextI18n")
    override fun showQuarter(quarter: String) {
        // 显示本季度
        onStateChanged(MultiStateLayout.SUCCESS)
        mCurrentQ.text = "${quarter}月新番"
    }

    override fun showNewComics(newComics: List<IModel.IComicModel>) {
        BannerHelper.getBannerLayouts(mComicLatestBanner, newComics)
    }

    override fun showRecommendComics(recommendComics: List<IModel.IComicModel>) {
        mRecommendComicsList.clear()
        mRecommendComicsList.addAll(recommendComics)
        mComicRecommendAdapter.notifyDataSetChanged()
    }

    override fun showNewComments(newComment: List<IModel.ICommentModel>) {
        mComicNewCommentsList.clear()
        mComicNewCommentsList.addAll(newComment)
        mComicNewCommentsAdapter.notifyDataSetChanged()
    }

    override fun showGuessLikeComics(guessLikeComics: List<IModel.IComicModel>) {
        if (guessLikeComics.isEmpty()) {
            mLlComicGuessLikeLayout.visibility = View.GONE
        } else {
            mRvGuessLikeComics.adapter = HomeAnimeRecommendAdapter(guessLikeComics, activity)
            mRvGuessLikeComics.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
        }
    }

    override fun isActive(): Boolean {
        return isAdded
    }

    override fun getViewContext(): Context {
        return activity
    }

    override fun onResume() {
        super.onResume()
        mComicLatestBanner.startTurning(4000L)
    }

    override fun onPause() {
        super.onPause()
        mComicLatestBanner.stopTurning()
    }

    /**
     * 改变状态
     * @param state 状态 [MultiStateLayout.LOADING] [MultiStateLayout.NET_ERROR] [MultiStateLayout.SUCCESS]
     */
    private fun onStateChanged(state: Int) {
        mComicSwipeRefreshLayout?.isRefreshing = false
        mComicMultiStateLayout?.changeState(state)
    }

    companion object {
        private var FRAGMENT_INSTANCE: ComicFragment? = null

        /**
         * 获取实例
         */
        fun getInstance(): ComicFragment {
            if (FRAGMENT_INSTANCE == null) {
                FRAGMENT_INSTANCE = ComicFragment()
            }
            return FRAGMENT_INSTANCE!!
        }

        /**
         * 销毁实例
         */
        fun destroyInstance() {
            FRAGMENT_INSTANCE = null
        }
    }

    /**
     * 新番速递适配器
     * Created by shize on 2017/10/20.
     */
    private class ComicBannerAdapter constructor(private val mContext: Context,
                                                 private val mComics: List<IModel.IComicModel>,
                                                 private val mBanner: BannerViewPager)
        : BannerViewPager.BannerViewPagerAdapter() {
        @SuppressLint("SetTextI18n")
        override fun createPager(container: ViewGroup?, position: Int): View {
            val pager: View = LayoutInflater.from(mContext).inflate(R.layout.item_comic_latest_anime, container, false)
            val comic = mComics[position] as ComicModel
            Glide.with(mContext)
                    .load(comic.imgUrl)
                    .bitmapTransform(CenterCrop(mContext), GlideRoundTransform(mContext, 2))
                    .into(pager.findViewById(R.id.roundedImageView) as ImageView)
            (pager.findViewById(R.id.mTvComicLatestTitle) as TextView).text = comic.title
            (pager.findViewById(R.id.mTvComicLatestType) as TextView).text = comic.genre
            (pager.findViewById(R.id.mTvComicLatestDirector) as TextView).text = comic.director
            (pager.findViewById(R.id.mTvComicLatestUpdateInfo) as TextView).text = "${comic.insertTime} 更新至第${comic.episodes}话"
            container!!.addView(pager)
            mBanner.addViewWithPosition(pager, position)
            return pager
        }

        override fun isViewFromObject(view: View?, `object`: Any?): Boolean = view == `object`

        override fun getCount(): Int = mComics.size
    }


    /**
     * 最新槽点
     * Created by alex on 2017/11/20.
     */
    private class ComicTucaoAdapter constructor(private val mContext: Context,
                                                private val mComments: List<IModel.ICommentModel>) : RecyclerView.Adapter<ComicTucaoAdapter.ViewHolder>() {
        override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
            val comment = mComments[position] as CommentModel
            holder!!.mUserName.text = comment.user.userName
            Glide.with(mContext).load(comment.user.avatarUrl)
                    .bitmapTransform(CenterCrop(mContext), GlideRoundTransform(mContext, 10))
                    .placeholder(R.mipmap.avatar)
                    .into(holder.mUserAvatar)
            holder.mAnimeTitle.text = comment.title
            holder.mComment.text = comment.content
            holder.mTime.text = comment.createTime
            holder.mAnimeContainer.onClick {
                val intent = Intent(mContext, SingleActivity::class.java)
                intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_ANIME_INFO)
                intent.putExtra(SingleActivity.BUNDLE_EXTRA_KEY_ID, comment.subjectId)
                ActivityHelper.startActivity(mContext as Activity, intent)
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
            return ViewHolder(View.inflate(mContext, R.layout.item_comic_latest_tucao, null))
        }

        override fun getItemCount(): Int {
            return mComments.size
        }

        class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val mUserName = itemView.mTvComicTucaoUserName as TextView
            val mUserAvatar = itemView.mIvComicTucaoAvatar as ImageView
            val mAnimeCover = itemView.mIvComicTucaoAnimeCover as ImageView
            val mAnimeTitle = itemView.mTvComicTucaoAnimeTitle as TextView
            val mComment = itemView.mTvComicTucaoContent as TextView
            val mAnimeContainer = itemView.mLlComicTucaoAnimeContainer as LinearLayout
            val mTime = itemView.mTvComicTucaoTime as TextView
        }

    }
}